/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package cn.edu.ntu.yyl.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;

public class LayuiTool {
    //对象转化为Layui格式的JSON
    public static String objectToJsonString(Object object){
        String code = "\"code\": 0,";
        String msg = "\"msg\": \"返回成功\",";
        String count = "\"count\": 1,";
        String data = "\"data\": ["+ JSON.toJSONString(object,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullBooleanAsFalse)
                +"]";
        return "{" + "\n" +
                code + "\n" +
                msg + "\n" +
                count + "\n" +
                data + "\n" +
                "}";
    }
    //对象数组转化为Layui格式的JSON
    public static String objectToJsonString(List<Object> objectList){
        String Listcode = "\"code\": 0,";
        String Listmsg = "\"msg\": \"返回成功\",";
        String Listcount = "\"count\": "+ objectList.size()+",";
        String datas = JSON.toJSONString(objectList,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullBooleanAsFalse);
        String Listdata = "\"data\": "+ datas;
        JSONObject.parse("");
        return "{" + "\n" +
                Listcode + "\n" +
                Listmsg + "\n" +
                Listcount + "\n" +
                Listdata + "\n" +
                "}";
    }
    public static Object objectToJSON(List<Object> objectList){
        return JSON.parse(objectToJsonString(objectList));
    }
    public static Object objectToJSON(Object object){
        return JSON.parse(objectToJsonString(object));
    }
}
